<script setup lang='ts'>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProducts } from '../../composables/useProducts'
import { useCart } from '../../composables/useCart'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../../stores/auth'

const route = useRoute()
const router = useRouter()
const { products, loading } = useProducts()
const { addToCart } = useCart()
const auth = useAuthStore()

const categories = [
  '男装','女装','运动鞋','休闲鞋','办公用品','书籍','笔记本','手机','平板电脑','烹饪食材','白酒','茶叶','咖啡'
]

const current = ref<string>(String(route.params.category || ''))
watch(() => route.params.category, (v) => { current.value = String(v || '') })

const keyword = ref('')

function belongsToCategory(item: any, cat: string): boolean {
  const text = `${item?.name || ''} ${item?.description || ''} ${item?.category || ''}`.toLowerCase()
  const map: Record<string, string[]> = {
    '男装': ['男','男装','men','male'],
    '女装': ['女','女装','women','female'],
    '运动鞋': ['运动鞋','跑鞋','耐克','阿迪','运动'],
    '休闲鞋': ['休闲鞋','板鞋','休闲'],
    '办公用品': ['办公','文具','订书机','打印','办公用品'],
    '书籍': ['书','图书','读物','书籍','小说'],
    '笔记本': ['笔记本','laptop','notebook'],
    '手机': ['手机','phone','移动电话'],
    '平板电脑': ['平板','pad','tablet'],
    '烹饪食材': ['食材','烹饪','厨房','米','面','油'],
    '白酒': ['白酒','酒','酱香','浓香'],
    '茶叶': ['茶','茶叶','绿茶','红茶','乌龙'],
    '咖啡': ['咖啡','coffee','拿铁','美式'],
  }
  if (String(item?.category || '').includes(cat)) return true
  const kws = map[cat] || []
  return kws.some(k => text.includes(k))
}

const filtered = computed(() => {
  const kw = keyword.value.trim().toLowerCase()
  let list = products.value as any[]
  if (current.value) {
    list = list.filter(i => belongsToCategory(i, current.value))
  }
  if (kw) {
    list = list.filter(i =>
      String(i.name || '').toLowerCase().includes(kw) ||
      String(i.description || '').toLowerCase().includes(kw)
    )
  }
  return list
})

function jump(cat: string) {
  router.push({ path: `/client/category/${encodeURIComponent(cat)}` })
}

function goDetail(id: string | number) {
  router.push({ path: `/client/product/${id}` })
}

function handleAdd(item: any) {
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  addToCart(item, 1)
  ElMessage.success('已加入购物车')
}
</script>

<template>
  <div class="cat-page">
    <el-row :gutter="16">
      <el-col :span="5">
        <el-card class="side">
          <div class="side-title">商品分类</div>
          <div class="cats">
            <a :class="['cat', { active: !current }]" @click="jump('')">全部</a>
            <a v-for="c in categories" :key="c" :class="['cat', { active: current===c }]" @click="jump(c)">{{ c }}</a>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card>
          <div class="toolbar">
            <div class="left">
              <div class="title">{{ current || '全部商品' }}</div>
              <div class="count">共 {{ filtered.length }} 件</div>
            </div>
            <el-input v-model="keyword" placeholder="搜索该分类下商品" style="max-width: 260px" />
          </div>
          <el-skeleton :loading="loading" animated :rows="6">
            <template #default>
              <el-row :gutter="16" class="grid">
                <el-col :span="6" v-for="item in filtered" :key="item.id">
                  <div class="card">
                    <div class="img-wrap" @click="goDetail(item.id)">
                      <img :src="item.imgs" />
                    </div>
                    <div class="name" @click="goDetail(item.id)">{{ item.name }}</div>
                    <div class="price">￥{{ item.saleMoney }}</div>
                    <div class="desc">{{ item.description }}</div>
                    <el-button type="success" round style="width: 100%;" @click="handleAdd(item)">加入购物车</el-button>
                  </div>
                </el-col>
              </el-row>
              <el-empty v-if="!filtered.length" description="暂无商品" />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.cat-page{ width: 97.5%; margin: 16px auto; }
.side{ border-radius: 10px; }
.side-title{ font-weight: 700; margin-bottom: 10px; }
.cats{ display: flex; flex-wrap: wrap; gap: 8px; }
.cat{ padding: 6px 10px; border-radius: 6px; background: #f5f7fa; cursor: pointer; color: #606266; }
.cat.active{ background: #e1f3d8; color: #67c23a; }
.toolbar{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.toolbar .left{ display: flex; align-items: baseline; gap: 12px; }
.toolbar .title{ font-size: 20px; font-weight: 700; }
.toolbar .count{ color: #909399; }
.grid :deep(.el-col){ margin-bottom: 16px; }
.card{ background: #fff; border-radius: 10px; padding: 12px; transition: box-shadow .2s; }
.card:hover{ box-shadow: 0 8px 24px rgba(0,0,0,.08); }
.img-wrap{ width: 100%; height: 220px; cursor: pointer; }
.img-wrap img{ width: 100%; height: 100%; object-fit: cover; border-radius: 6px; }
.name{ margin: 8px 0 4px; text-align: center; cursor: pointer; }
.price{ color: #f56c6c; text-align: center; }
.desc{ font-size: 12px; color: #666; height: 40px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; margin: 6px 8px; }
</style>

